<?php 
//获取任何网站信息
class GetItemModel{
	public function getItems($url){
		//淘宝商城
		if(strpos($url,'http://detail.tmall.com/item.htm')===0){
			return $this->getTmailItems($url);	
		}
		//淘宝
		elseif(strpos($url,'http://item.taobao.com/item.htm')===0){
			return $this->getTaobaoItems($url);
		}
		else{
			$content = url_get_contents($url);
			return array(
				'ProductName'=>$this->getTitle($content),
				'Price'=>0,
				'Thumbnail'=>'',
			);
		}

	}
	public function getTmailItems($url){
		return $this->getTaobaoItems($url);
	}
	public function getTaobaoItems($url){
		$content = url_get_contents($url);
		//$content = file_get_contents('tm.txt');
		$rule = '<div id="J_itemViewed" [变数] data-value=\'[JSON]\'></div>';
		$tag = array('json'=>'[JSON]');
		$match = easy_match_all($content,$rule,$tag,'[变数]');
		$json = $match['json'] ? $match['json'][0]:array();
		/*
		得到的返回值是：
		{"itemId":"16802318914","xid":"","pic":"i2/19770021081042933/T1SQF0XxhXXXXXXXXX_!!0-item_pic.jpg","price":"25000","itemIdStr":"16802318914","title":"Johnnie walker尊尼获加黑牌威士忌700ML新风尚赠品加倍4.12-4.15"}
		*/
		$items = array();
		if($json){
			$json = json_decode(iconv("gbk","utf-8",$json));
			$items['ProductName'] = $json->title;
			$items['Price'] = sprintf('%0.2f',($json->price)/100);
			$items['Thumbnail'] = 'http://img03.taobaocdn.com/bao/uploaded/'.$json->pic;
		}
		//如果没有items,则换种方式
		if(!$items){
			$rule = '<form id="J_FrmBid" name="bidForm" action="" method="post">[标签]</form>';
			$form_str = $this->getByTag($content,$rule);
			$rule = '<input type="hidden" name="title" value="[标签]" />';
			$items['ProductName'] = iconv('gbk','utf-8',$this->getByTag($form_str,$rule));
			$rule = '<input type="hidden" name="price" value="[标签]" />';
			$items['price'] = $this->getByTag($form_str,$rule);
			$rule = '<input type="hidden" name="photo_url" value=[变数]"[标签]" />';
			$items['Thumbnail'] = 'http://img03.taobaocdn.com/bao/uploaded/'.$this->getByTag($form_str,$rule);
		}

		if(!$items || !$items['ProductName']){
			$items['ProductName'] = $this->getTitle($content);
		}
		return $items;
	}

	public function getTitle($content){
		if(!$content) return '';
		$rule = '<title>[标题]</title>';
		$tag = array('title'=>'[标题]');
		$match = easy_match_all($content,$rule,$tag,'[变数]');
		return iconv('gbk','utf-8',$match['title'][0]);
	}

	public function getByTag($str,$rule,$tag='[标签]'){
		$match = easy_match_all($str,$rule,$tag,'[变数]');
		$str = $match[0] ? trim($match[0][0]):array();
		return $str;
	}
}